package com.longqinuo.mycarservice.fragments;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;


import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.adapter.CarBrandAdapter;
import com.longqinuo.mycarservice.adapter.IndexBarAdapter;
import com.longqinuo.mycarservice.entity.CarBrand;
import com.longqinuo.mycarservice.utils.ComparatorPersonToPinYin;
import com.longqinuo.mycarservice.utils.PathUtils;

import net.sourceforge.pinyin4j.PinyinHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SelectedBrandFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SelectedBrandFragment extends Fragment implements View.OnClickListener,AdapterView.OnItemClickListener{
    private ImageView mBack;
    private TextView mTitle;
    private ImageView mEdit;
    private FragmentManager manager;

    private ListView listView;    //快递号码列表视图
    private ListView mIndexBar; //快速索引条
    private ListView mTypeLv; //车系列表
    private ArrayAdapter mAdapter;
    private PopupWindow popupWindow;
    private LinearLayout topBar; //顶部标题栏
    private List<String> typeList;
    private String types[] = {
            "A3","A4L","A6l","Q3","Q5","A4","A6","A1","A3","S3","X5","X7","X8","U3","U5"
    };
    private TextView mIndexNoti;
    private List<String> chs;  //快速索引条字母集合
    private int height; // 索引布局高度
    private List<CarBrand> mList;
    private String mName;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public SelectedBrandFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SelectedBrandFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SelectedBrandFragment newInstance(String param1, String param2) {
        SelectedBrandFragment fragment = new SelectedBrandFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_selected_brand, container, false);
        //初始化主列表数据集合
        initData();
        dataDeal();
        initView(view);
        return view;
    }

    private void initView(View view) {
        manager = getActivity().getSupportFragmentManager();
        topBar = (LinearLayout) view.findViewById(R.id.ll_top_bar); //顶部标题栏
        mTypeLv = (ListView) view.findViewById(R.id.lv_type_list);
        listView = (ListView) view.findViewById(R.id.lv_car_brand);
        mIndexBar = (ListView) view.findViewById(R.id.lv_index_bar);
        mIndexNoti = (TextView) view.findViewById(R.id.tv_index_noti);
        mBack = (ImageView) view.findViewById(R.id.iv_top_back);
        mTitle = (TextView) view.findViewById(R.id.tv_top_title);
        mEdit = (ImageView) view.findViewById(R.id.iv_top_option);
        mBack.setOnClickListener(this);
        mTitle.setText("选择车品牌");
        mEdit.setVisibility(View.INVISIBLE);
        listView.setAdapter(new CarBrandAdapter(getActivity(),mList));

        listView.setOnItemClickListener(this);

        height = mIndexBar.getHeight();
        //完成右边边界绘制
        finishRightLayout(mList);
    }
    private void setAlpha(float alpha) {  //设置popupWindow之外的透明度
        Window w = getActivity().getWindow();
        WindowManager.LayoutParams lp = w.getAttributes();
        lp.alpha = alpha;
        w.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        w.setAttributes(lp);
    }
    private void dataDeal() {
        // 取得拼音
        for (CarBrand c : mList) {
            // 取得拼音
            c.setPinYinName(getPinYinNameHeader(c.getName()));
        }
        // 排序
        Collections.sort(mList, new ComparatorPersonToPinYin());
        //插入值
        String tempCh = "1";
        for (int i =0; i< mList.size(); i ++  ) {
            if (!tempCh.equals(mList.get(i).getPinYinName().charAt(0)+"")) {
                mList.add(i, new CarBrand(0,"",mList.get(i).getPinYinName().charAt(0)+""));
                tempCh = mList.get(i).getPinYinName().charAt(0)+"";
            }
        }
    }
    private void initData() {
        mList = new ArrayList<CarBrand>();
        for (int i = 0; i < PathUtils.names.length; i++) {
            CarBrand carBrand = new CarBrand();
            carBrand.setLogo(R.mipmap.ic_launcher);
            carBrand.setName(PathUtils.names[i]);
            mList.add(carBrand);
        }

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }
    //完成右边界面
    private void finishRightLayout(List<CarBrand> chars) {
        chs = new ArrayList<String>();
        for (CarBrand carBrand : chars) {
            if (carBrand.getName().equals("")) {
                chs.add(carBrand.getPinYinName());
            }
        }
        mIndexBar.setAdapter(new IndexBarAdapter(getActivity(),chs,height));
        mIndexBar.setOnItemClickListener(this);
    }





    // 得到名字拼音头字母
    public String getPinYinNameHeader(String str) {
        String convert = "";
        for (int i = 0; i < str.length(); i++) {
            char word = str.charAt(i);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_top_back:
                manager.popBackStack();
                break;
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.lv_car_brand:  //主内容ListView
                CarBrand brand  = mList.get(position);
                mName = brand.getName();
                String pinyinName = brand.getPinYinName().toUpperCase();
                if (mName.equals("")) {
                    mIndexNoti.setVisibility(View.VISIBLE);
                    mIndexNoti.setText(pinyinName);
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mIndexNoti.setVisibility(View.GONE);
                                }
                            });
                        }
                    }.start();

                } else {
                    typeList = new ArrayList<>();
                    String carName = mList.get(position).getName();
                    for (int i = 0; i < types.length; i++) {
                        typeList.add(carName+types[i]);
                    }
                    View v = View.inflate(getActivity(),R.layout.car_type_list,null);
                    mTypeLv = (ListView) v.findViewById(R.id.lv_type_list);
                    mAdapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,typeList);
                    mTypeLv.setAdapter(mAdapter);
                    popupWindow = new PopupWindow(v, ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
                    mTypeLv.setOnItemClickListener(this);

                    setAlpha(0.8f);
                    popupWindow.setTouchable(true);
                    popupWindow.setFocusable(true);
                    popupWindow.setBackgroundDrawable(new BitmapDrawable());
                    popupWindow.setOutsideTouchable(true);
                    popupWindow.showAsDropDown(topBar,0,0, Gravity.RIGHT);
                    popupWindow.update();
                    popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            setAlpha(1.0f);
                        }
                    });
                }
                break;
            case R.id.lv_index_bar: //索引条ListView
                String ch = chs.get(position);
                int count = 0;
                for (int i = 0; i< mList.size(); i ++) {
                    if (mList.get(i).getPinYinName().equals(ch)) {
                        count = i;
                    }
                    if (listView.getHeaderViewsCount() > 0) {
                        listView.setSelectionFromTop(count+listView.getHeaderViewsCount(), 0);
                    } else {
                        listView.setSelectionFromTop(count, 0);
                    }
                }
                mIndexNoti.setVisibility(View.VISIBLE);
                mIndexNoti.setText(ch.toUpperCase());
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mIndexNoti.setVisibility(View.GONE);
                            }
                        });
                    }
                }.start();
                break;
            case R.id.lv_type_list: //PopupWindow
                popupWindow.dismiss();
                break;
        }
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
